package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.model.mess.app.ArticleVisitStreamMess;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void computeHotArticle() {
        //1 查询前5天的 （已上架、未删除） 文章数据
        //1.1 查询出5天前的时间
        String dayParam = LocalDateTime.now().minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //1.2 调用apArticleMapper根据时间查询
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(dayParam);
//        System.out.println(articleList);
        //2 计算热点文章分值
      List<HotArticleVo> hotArticleVoList=getHotArticleVoList(articleList);

        //3 为每一个频道缓存热点较高的30条文章
        cacheToRedisByTag(hotArticleVoList);

    }

    @Override
    public void updateApArticle(AggBehaviorDTO aggBehavior) {
        // 1 根据文章id 查询出文章数据
        ApArticle article = apArticleMapper.selectById(aggBehavior.getArticleId());
        if (article==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        // 2 根据聚合结果 更新文章各行为参数
        article.setViews((int)(article.getViews()==null?aggBehavior.getView():article.getViews()+aggBehavior.getView()));

        article.setLikes((int)(article.getLikes()==null?aggBehavior.getLike():article.getLikes()+aggBehavior.getLike()));
        article.setComment((int)(article.getComment()==null?aggBehavior.getComment():article.getComment()+aggBehavior.getComment()));
        article.setCollection((int)(article.getCollection()==null?aggBehavior.getCollect():article.getCollection()+aggBehavior.getCollect()));
        // 修改文章行为数量
        apArticleMapper.updateById(article);
        // 3 重新计算改文章得分
        Integer score = computeScore(article);
        // 4 判断文章是否当日发布 如实 热度*3
        String newStr= DateUtils.dateToString(new Date());
        String publishStr=DateUtils.dateToString(article.getPublishTime());
        if (newStr.equals(publishStr)){
            score=score*3;
        }
        // 5 更新频道文章缓存
        updateActicleCache(article,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+article.getChannelId());
        // 6 更新推荐热点文章缓存
        updateActicleCache(article,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 更新缓存 热度分 更新redis缓存
     * @param article
     * @param score
     * @param cacheKey
     */
    private void updateActicleCache(ApArticle article, Integer score, String cacheKey) {
        // 1 根据缓存key 查出 热点文章数据
        String hotArticleJson = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(hotArticleJson)){
            log.error("热点文章 缓存为空");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        boolean isHas=false;
        // 2 判断当前文章是否在热点文章中列表
        for (HotArticleVo articleVo : hotArticleVoList) {
            // 如果集合中 包含当前文章
            if (articleVo.getId().equals(article.getId())){
                // 修改得分
               articleVo.setScore(score);
                isHas=true;
               break;
            }
        }
        // 3 如果不在 直接将文章加入到热点文章列表中
        if (!isHas){
            HotArticleVo articleVo = new HotArticleVo();
            BeanUtils.copyProperties(article,articleVo);
            articleVo.setScore(score);
            hotArticleVoList.add(articleVo);
        }
        // 4 将文章集合 按照得分降低排序 截获30条热点文章
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        // 5 重新将热点文章集合 保存到redis
        redisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleVoList));
        redisTemplate.expire(cacheKey,2, TimeUnit.DAYS);
    }


    @Autowired
    AdminFeign adminFeign;

    /**
     * 按照频道 将热点文章缓存
     * @param hotArticleVoList
     */
    private void cacheToRedisByTag(List<HotArticleVo> hotArticleVoList) {
        //1 远程查询频道列表
        ResponseResult<List<AdChannel>> result = adminFeign.selectChannels();
        if (!result.checkCode()){
            log.error("远程调用失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"adminFeign远程调用失败");
        }
        List<AdChannel> channelList = result.getData();
        if (CollectionUtils.isEmpty(channelList)){
            log.error("未查询到频道相关数据");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到频道相关数据");
        }
        //2 遍历频道 找出每个频道的文章 进行缓存
        for (AdChannel channel : channelList) {
            List<HotArticleVo> articleVoByChannel = hotArticleVoList.stream()
                    .filter(articleVo -> articleVo.getChannelId().equals(channel.getId()))
                    .collect(Collectors.toList());
            // 将集合缓存
            sortAndCache(articleVoByChannel,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channel.getId());
        }
        //3 推荐频道缓存
        sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 将文章 按照热度排序 降序
     * 排序后将前30条文章
     * 存入redis
     * @param articleVoList
     * @param cacheKey
     */

    @Autowired
    StringRedisTemplate redisTemplate;

    private void sortAndCache(List<HotArticleVo> articleVoList, String cacheKey) {
//             将文章 按照热度排序 降序
        List<HotArticleVo> hotArticleList = articleVoList.stream().sorted(Comparator
                .comparing(HotArticleVo::getScore).reversed())
//        排序后将前30条文章
                .limit(30)
                .collect(Collectors.toList());
//                存入redis
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleList));

    }

    /**
     * 计算每一篇文章的分值将article->articleVo
     * @param articleList
     * @return
     */
    private List<HotArticleVo> getHotArticleVoList(List<ApArticle> articleList) {
        return articleList.stream().map(apArticle -> {
            HotArticleVo articleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,articleVo);
            // 计算文章热度
            articleVo.setScore(computeScore(apArticle));
            return articleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算得分
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score=0;
        if (apArticle.getViews()!=null) {
            score+=apArticle.getViews()* ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if (apArticle.getLikes()!=null) {
            score+=apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getComment()!=null) {
            score+=apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection()!=null) {
            score+=apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
